//
//  GCBSearchBar.m
//  LeconsOS
//
//  Created by 李勤超 on 2018/9/19.
//  Copyright © 2018年 江苏乐建网络科技有限公司. All rights reserved.
//

#import "GCBSearchBar.h"
#import "UIView+NTES.h"

#define FRAME_SELF_X self.frame.origin.x
#define FRAME_SELF_Y self.frame.origin.y
#define FRAME_SELF_W self.width
#define FRAME_SELF_H self.height

@interface GCBSearchBar ()<UITextFieldDelegate>

@property (nonatomic) CGRect textFieldFrame;

@end

@implementation GCBSearchBar

+ (instancetype)searBarWithFrame:(CGRect)frame
                     placeholder:(NSString *)placeholder
                  cancelShowType:(GCBSearchBarCancelShowType)type
                        delegate:(id)delegate
{
    return [[self alloc] initWithFrame:frame
                           placeholder:placeholder
                        cancelShowType:type
                              delegate:delegate];
}
- (instancetype)initWithFrame:(CGRect)frame
                  placeholder:(NSString *)placeholde
               cancelShowType:(GCBSearchBarCancelShowType)type
                     delegate:(id)delegate
{
    frame.size.height = GCBSearchBarHeight;
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        _placeholder = placeholde ? : @"搜索";
        [self initPropertys:type];
        self.delegate = delegate;
    }
    return self;
}
- (void)initPropertys:(GCBSearchBarCancelShowType)type{
    _textFieldInsets = UIEdgeInsetsMake(10.f, 15.f, 10.f, 15.f);
    _textColor_placeholder = HexColor(0x939ba4);
    _textColor = HexColor(0x333333);
    _backgroundColor_textField = HexColor(0xedf0f4);
    self.placeholder = _placeholder;
    _cancelButtonTitle = type == GCBSearchBarCancelShowTypeScreening ? @" 筛选" : @"取消";
    _backgroundColor_cancelButton = [UIColor clearColor];
    self.cancelButtonFont = 15.0;
    self.textColor_cancelButton = type == GCBSearchBarCancelShowTypeScreening ? HexColor(0x939ba4) : HexColor(0x333333);
    if (type == GCBSearchBarCancelShowTypeAlways) {
        self.textColor_cancelButton = HexColor(0x333333);
    }
    self.cancelShowsType = type;
    self.font = 14.0;
    self.font_placeholder = 13.0;
}
- (CGRect)textFieldFrame{
    CGFloat cancelBtnW = FRAME_SELF_W - (_textFieldInsets.left + _textFieldInsets.right);
    if (_cancelButton && !_cancelButton.hidden) {
        cancelBtnW = FRAME_SELF_W - _textFieldInsets.left - _cancelButton.width;
    }
    return CGRectMake(_textFieldInsets.left, _textFieldInsets.top, cancelBtnW, FRAME_SELF_H - (_textFieldInsets.top + _textFieldInsets.bottom));
}
#pragma mark -- set方法
- (void)setTextFieldInsets:(UIEdgeInsets)textFieldInsets{
    _textFieldInsets = textFieldInsets;
    _textField.frame = self.textFieldFrame;
}
- (void)setPlaceholder:(NSString *)placeholder{
    _placeholder = placeholder;
    if (!_textField) {
        [self initSubViews];
    }
    _textField.placeholder = placeholder;
}
- (void)setBackgroundColor_textField:(UIColor *)backgroundColor_textField{
    _backgroundColor_textField = backgroundColor_textField;
    _textField.backgroundColor = backgroundColor_textField;
}
- (void)setFont:(CGFloat)font{
    _font = font;
    _textField.font = [UIFont systemFontOfSize:font];
    if (_font_placeholder > 0) {
        [_textField setValue:[UIFont systemFontOfSize:_font_placeholder] forKeyPath:@"_placeholderLabel.font"];
    }
}
- (void)setFont_placeholder:(CGFloat)font_placeholder{
    _font_placeholder = font_placeholder;
//    [_textField setValue:[UIFont systemFontOfSize:font_placeholder] forKeyPath:@"_placeholderLabel.font"];
}
-(void)setTextColor:(UIColor *)textColor{
    _textColor = textColor;
    _textField.textColor = textColor;
}
- (void)setTextColor_placeholder:(UIColor *)textColor_placeholder{
    _textColor_placeholder = textColor_placeholder;
//    [_textField setValue:textColor_placeholder forKeyPath:@"_placeholderLabel.textColor"];
}
- (void)setCancelShowsType:(GCBSearchBarCancelShowType)cancelShowsType{
    _cancelShowsType = cancelShowsType;
    if (!_cancelButton && cancelShowsType != GCBSearchBarCancelShowTypeNone) {
        [self initCancelButton];
    }
    if (cancelShowsType == GCBSearchBarCancelShowTypeAlways) {
        _cancelButton.hidden = NO;
        _textField.frame = self.textFieldFrame;
    }
    if (cancelShowsType == GCBSearchBarCancelShowTypeScreening) {
        _cancelButton.hidden = NO;
        [_cancelButton setImage:[UIImage imageNamed:@"icon_filter"] forState:(UIControlStateNormal)];
        _cancelButton.frame = CGRectMake(FRAME_SELF_W - 75.0, 0, 75.0, FRAME_SELF_H);
        _textField.frame = self.textFieldFrame;
    }
}
- (void)setCancelButtonFont:(CGFloat)cancelButtonFont{
    _cancelButtonFont = cancelButtonFont;
    if (!_cancelButton) {
        [self initCancelButton];
    }
    _cancelButton.titleLabel.font = [UIFont systemFontOfSize:cancelButtonFont];
}
- (void)setTextColor_cancelButton:(UIColor *)textColor_cancelButton{
    _textColor_cancelButton = textColor_cancelButton;
    if (!_cancelButton) {
        [self initCancelButton];
    }
    [_cancelButton setTitleColor:textColor_cancelButton forState:(UIControlStateNormal)];
}
- (void)setBackgroundColor_cancelButton:(UIColor *)backgroundColor_cancelButton{
    _backgroundColor_cancelButton = backgroundColor_cancelButton;
    if (!_cancelButton) {
        [self initCancelButton];
    }
    [_cancelButton setBackgroundColor:backgroundColor_cancelButton];
}
- (void)setCancelButtonTitle:(NSString *)cancelButtonTitle{
    _cancelButtonTitle = cancelButtonTitle;
    if (!_cancelButton) {
        [self initCancelButton];
    }
    [_cancelButton setTitle:_cancelButtonTitle forState:(UIControlStateNormal)];
}
- (void)setReturnKeyType:(UIReturnKeyType)returnKeyType{
    _returnKeyType = returnKeyType;
    _textField.returnKeyType = _returnKeyType;
}
#pragma mark -- 初始化子控件
- (void)initSubViews{
    _textField = [[GCBTextField alloc] initWithFrame:self.textFieldFrame];
    _textField.layer.cornerRadius = 15.0;
    _textField.delegate = self;
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
//    [_textField setValue:_textColor_placeholder forKeyPath:@"_placeholderLabel.textColor"];
    _textField.textColor = _textColor;
    _textField.placeholder = _placeholder;
    _textField.backgroundColor = _backgroundColor_textField;
    [_textField addTarget:self action:@selector(textBeginEditing) forControlEvents:(UIControlEventEditingDidBegin)];
    [_textField addTarget:self action:@selector(textEndEditing) forControlEvents:(UIControlEventEditingDidEnd)];
    [_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    
//    UIImageView *imgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gcbSearchBar_leftImg_white"]];
//    imgV.frame = CGRectMake(0, 0, 30.0, 26.0);
//    imgV.contentMode = UIViewContentModeCenter;
    _textField.leftView = self.textField_LeftImgView;
    _textField.leftViewMode = UITextFieldViewModeAlways;
    [self addSubview:_textField];
}

-(void)setTextField_LeftImg:(NSString *)textField_LeftImg {
    _textField_LeftImg = textField_LeftImg;
    _textField_LeftImgView.image = [UIImage imageNamed:textField_LeftImg];
}

- (void)initCancelButton{
    _cancelButton = [[UIButton alloc] initWithFrame:CGRectZero];
    [_cancelButton setBackgroundColor:_backgroundColor_cancelButton];
    [_cancelButton setTitle:_cancelButtonTitle forState:(UIControlStateNormal)];
    [_cancelButton setTitleColor:_textColor_cancelButton forState:(UIControlStateNormal)];
    [_cancelButton sizeToFit];
    CGFloat cancelW = _cancelButton.width + 15.0;
    _cancelButton.frame = CGRectMake(self.right - cancelW, 0, cancelW, self.height);
    _cancelButton.hidden = YES;
    [_cancelButton addTarget:self action:@selector(cancelBtnClick) forControlEvents:(UIControlEventTouchUpInside)];
    [self addSubview:_cancelButton];
}

-(UIImageView *)textField_LeftImgView {
    if (!_textField_LeftImgView) {
        _textField_LeftImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gcbSearchBar_leftImg"]];
        _textField_LeftImgView.frame = CGRectMake(0, 0, 30.0, 26.0);
        _textField_LeftImgView.contentMode = UIViewContentModeCenter;
    }
    return _textField_LeftImgView;
}

#pragma mark -- 取消点击
- (void)cancelBtnClick{
    if (_cancelShowsType == GCBSearchBarCancelShowTypeScreening) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(gcbSearchBarScreenOutButtonClicked:)]) {
            [self.delegate gcbSearchBarScreenOutButtonClicked:self];
        }
    } else {
        if (self.delegate && [self.delegate respondsToSelector:@selector(gcbSearchBarCancelButtonClicked:)]) {
            [self.delegate gcbSearchBarCancelButtonClicked:self];
        }
    }
    [self.textField resignFirstResponder];
}

#pragma mark -- textField action
- (void)textBeginEditing{
    [self hiddenCancel:NO];
}
- (void)textEndEditing{
    [self hiddenCancel:YES];
}
#pragma mark -- textField 动画
- (void)hiddenCancel:(BOOL)hidden{
    if (_cancelButton) {
        CGFloat cancelW = _cancelButton.width;
        _cancelButton.frame = CGRectMake(self.right - cancelW, 0, cancelW, self.height);
        if (_cancelShowsType == GCBSearchBarCancelShowTypeEditing) {
            [_cancelButton setHidden:hidden];
            
            CGFloat width;
            if (hidden) {
                width = CGRectGetWidth(self.textFieldFrame);
            } else {
                width = _textField.width - self.cancelButton.width;
            }
            [UIView animateWithDuration:0.2 animations:^{
                self.textField.frame = self.textFieldFrame;
            }];
        } else if(_cancelShowsType == GCBSearchBarCancelShowTypeAlways ||
                  _cancelShowsType == GCBSearchBarCancelShowTypeScreening) {
            
        } else {
            
        }
    }
}

#pragma mark -- textFieldDelegate


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (self.delegate && [self.delegate respondsToSelector:@selector(gcbSearchBarShouldBeginEditing:)]) {
        return [self.delegate gcbSearchBarShouldBeginEditing:self];
    } return YES;
}
- (void)textFieldDidChange:(UITextField *)textField{
    if (self.delegate && [self.delegate respondsToSelector:@selector(gcbSearchBarTextDidChanged:searchText:)]) {
        [self.delegate gcbSearchBarTextDidChanged:self searchText:textField.text];
    }
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if (self.delegate && [self.delegate respondsToSelector:@selector(gcbSearchBarDidBeginEditing:)]) {
        [self.delegate gcbSearchBarDidBeginEditing:self];
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (self.delegate && [self.delegate respondsToSelector:@selector(gcbSearchBarDidEndEditing:)]) {
        [self.delegate gcbSearchBarDidEndEditing:self];
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason API_AVAILABLE(ios(10.0)){
    if (self.delegate && [self.delegate respondsToSelector:@selector(gcbSearchBarDidEndEditing:reason:)]) {
        [self.delegate gcbSearchBarDidEndEditing:self reason:reason];
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(gcbSearchBarSearchButtonClicked:)]) {
            [self.delegate gcbSearchBarSearchButtonClicked:self];return NO;
        }
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(gcbSearchBar:shouldChangeCharactersInRange:replacementString:)]) {
        return [self.delegate gcbSearchBar:self shouldChangeCharactersInRange:range replacementString:string];
    }
    return YES;
}

- (void)becomeFirstResponder{
    [_textField becomeFirstResponder];
}
- (void)resignFirstResponder{
    [_textField resignFirstResponder];
}
@end



#pragma mark ----------------------- GCBTextField ----------------------------------------

@interface GCBTextField (){
    BOOL anima; //  只需要在结束和开始的时候需要动画
}
@end

@implementation GCBTextField

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.returnKeyType = UIReturnKeySearch;
        [self addTarget:self action:@selector(textBeginEditing:) forControlEvents:(UIControlEventEditingDidBegin)];
        [self addTarget:self action:@selector(textEndEditing:) forControlEvents:(UIControlEventEditingDidEnd)];
        [self addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    }return self;
}

- (CGRect)textRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, self.leftView.right, 1);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, self.leftView.right, 1);
}

- (void)textFieldDidChange:(UITextField *)textField{
    anima = NO;
}

- (void)textEndEditing:(UITextField *)textField{
    anima = YES;
}

- (void)textBeginEditing:(UITextField *)textField{
    anima = YES;
}
- (void)layoutViews{
    UIView *leftView = self.leftView;
    UIView *rightView = self.rightView;
    UIView *placeholderLabel;
    
    for (UIView *view in self.subviews) {
        if (self.text.length == 0) {
            if ([view isKindOfClass:NSClassFromString(@"UITextFieldLabel")]) {
                placeholderLabel = view;
            }
        }
        if ([view isKindOfClass:[UIButton class]] &&
            rightView != view) {
            UIButton *cleanBtn = (UIButton *)view;
            [cleanBtn setImage:[UIImage imageNamed:@"login_icon_delete"] forState:(UIControlStateNormal)];
            [cleanBtn setImage:[UIImage imageNamed:@"login_icon_delete"] forState:(UIControlStateHighlighted)];
            [cleanBtn setImage:[UIImage imageNamed:@"login_icon_delete"] forState:(UIControlStateSelected)];
        }
    }
    if (self.text.length == 0) {
        CGSize size = [placeholderLabel sizeThatFits:CGSizeMake(self.width, 22.0)];
        CGFloat labelW = MIN(self.width - placeholderLabel.left - 5.0, size.width);
        CGFloat leftViewL = MAX(0, (self.width - labelW) / 2.0 - (leftView.width / 2.0));
        if (anima && self.isEditing) {
            leftView.frame = CGRectMake(leftViewL, leftView.top, leftView.width,  leftView.height);
            placeholderLabel.frame = CGRectMake(leftView.right, placeholderLabel.top, labelW,  placeholderLabel.height);
        }
        [UIView animateWithDuration:anima ? 0.3 : 0.0 animations:^{
            leftView.frame = CGRectMake(self.isEditing ? 0.0 : leftViewL, leftView.top, leftView.width,  leftView.height);
            placeholderLabel.frame = CGRectMake(leftView.right, placeholderLabel.top, labelW,  placeholderLabel.height);
            self->anima = NO;
        }];
    }
}

- (void)layoutSubviews{
    [super layoutSubviews];
    [self layoutViews];
}


@end

